package org.university.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.university.dto.request.RegisterStudentRequestDTO;
import org.university.dto.request.RegisterTeacherRequestDTO;
import org.university.dto.response.UserResponseDTO;
import org.university.entity.Student;
import org.university.entity.Teacher;
import org.university.entity.User;
import org.university.repository.StudentRepository;
import org.university.repository.TeacherRepository;
import org.university.repository.UserRepository;
import org.university.util.PasswordUtil;
import org.university.util.ValidationUtils;

import java.time.LocalDateTime;

@Service
public class UserService {

    private final UserRepository userRepository;
    private final StudentRepository studentRepository;
    private final TeacherRepository teacherRepository;

    public UserService(UserRepository userRepository, StudentRepository studentRepository, TeacherRepository teacherRepository) {
        this.userRepository = userRepository;
        this.studentRepository = studentRepository;
        this.teacherRepository = teacherRepository;
    }

    /**
     * 注册学生
     */
    @Transactional
    public Student registerStudent(RegisterStudentRequestDTO requestDTO) {
        // 验证用户有效性
        ValidationUtils.validateUser(requestDTO);

        // 设置需要保存的学生信息
        Student student = new Student();
        student.setStudentId(requestDTO.getStudentId());
        student.setStudentName(requestDTO.getStudentName());
        student.setGender(requestDTO.getGender());
        student.setBirthDate(requestDTO.getBirthDate());
        student.setEnrollmentDate(requestDTO.getEnrollmentDate());
        student.setDeptId(requestDTO.getDeptId());
        student.setClassId(requestDTO.getClassId());
        student.setPhone(requestDTO.getPhone());
        student.setStudentName(requestDTO.getStudentName());
        student.setEmail(requestDTO.getEmail());
        student.setAddress(requestDTO.getAddress());

        // 设置user表信息，因为密码信息需要保存到user表
        User user = new User();
        user.setUserId(requestDTO.getStudentId());
        user.setUserName(requestDTO.getStudentName());
        user.setEmail(requestDTO.getEmail());
        user.setPasswordEncrypted(PasswordUtil.encodePassword(requestDTO.getPassword()));
        user.setRole(User.UserRole.valueOf(requestDTO.getRole()));

        // 保存到user表
        userRepository.save(user);

        // 保存到student表
        return studentRepository.save(student);
    }

    /**
     * 注册教师
     */
    @Transactional
    public Teacher registerTeacher(RegisterTeacherRequestDTO requestDTO) {
        // 验证用户有效性
        ValidationUtils.validateUser(requestDTO);

        // 设置需要保存的教师信息
        Teacher teacher = new Teacher();
        teacher.setTeacherId(requestDTO.getTeacherId());
        teacher.setTeacherName(requestDTO.getTeacherName());
        teacher.setGender(requestDTO.getGender());
        teacher.setBirthDate(requestDTO.getBirthDate());
        teacher.setHireDate(requestDTO.getHireDate());
        teacher.setDeptId(requestDTO.getDeptId());
        teacher.setTitle(requestDTO.getTitle());
        teacher.setPhone(requestDTO.getPhone());
        teacher.setEmail(requestDTO.getEmail());

        // 设置user表信息，因为密码信息需要保存到user表
        User user = new User();
        user.setUserId(requestDTO.getTeacherId());
        user.setUserName(requestDTO.getTeacherName());
        user.setEmail(requestDTO.getEmail());
        user.setPasswordEncrypted(PasswordUtil.encodePassword(requestDTO.getPassword()));
        user.setRole(User.UserRole.valueOf(requestDTO.getRole()));

        // 保存到user表
        userRepository.save(user);

        // 保存到teacher表
        return teacherRepository.save(teacher);
    }

    /**
     * 用户登录验证
     */
    public User authenticate(String userId, String password) {
        User user = userRepository.findByUserId(userId)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在"));

        if (!user.getStatus()) {
            throw new IllegalStateException("账号已被禁用");
        }

        if (!PasswordUtil.matches(password, user.getPasswordEncrypted())) {
            throw new IllegalArgumentException("密码错误");
        }

        // 更新最后登录时间
        user.setLastLogin(LocalDateTime.now());
        userRepository.save(user);

        return user;
    }

    /**
     * 修改密码
     */
    @Transactional
    public void changePassword(String userId, String oldPassword, String newPassword) {
        User user = userRepository.findByUserId(userId)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在"));

        if (!PasswordUtil.matches(oldPassword, user.getPasswordEncrypted())) {
            throw new IllegalArgumentException("原密码错误");
        }

        user.setPasswordEncrypted(PasswordUtil.encodePassword(newPassword));
        userRepository.save(user);
    }


    /**
     * 将用户实体转换为响应DTO，避免返回敏感信息
     */
    public static UserResponseDTO convertToUserResponseDTO(Student student) {
        UserResponseDTO dto = new UserResponseDTO();
        // dto.setId(student.getId());
        dto.setUserId(student.getStudentId());
        dto.setUsername(student.getStudentName());
        dto.setRole(String.valueOf(User.UserRole.STUDENT));
        dto.setEmail(student.getEmail());
        // dto.setCreatedAt(student.getCreatedAt());
        // 不返回密码等敏感字段
        return dto;
    }

    public static UserResponseDTO convertToUserResponseDTO(Teacher teacher) {
        UserResponseDTO dto = new UserResponseDTO();
        // dto.setId(teacher.getId());
        dto.setUserId(teacher.getTeacherId());
        dto.setUsername(teacher.getTeacherName());
        dto.setRole(String.valueOf(User.UserRole.STUDENT));
        dto.setEmail(teacher.getEmail());
        // dto.setCreatedAt(teacher.getCreatedAt());
        // 不返回密码等敏感字段
        return dto;
    }
}